package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.TPlatformInfo;
import com.ruoyi.system.domain.TPrivilegeVerification;
import com.ruoyi.system.mapper.TPlatformInfoMapper;
import com.ruoyi.system.mapper.TPrivilegeVerificationMapper;
import com.ruoyi.system.service.ITPrivilegeVerificationService;

/**
 * 特权免押Service业务层处理
 * 
 * @author xiuddooo
 * @date 2025-10-10
 */
@Service
public class TPrivilegeVerificationServiceImpl implements ITPrivilegeVerificationService 
{
    @Autowired
    private TPrivilegeVerificationMapper tPrivilegeVerificationMapper;
    @Autowired
    private TPlatformInfoMapper tPlatformInfoMapper;

    /**
     * 查询特权免押
     * 
     * @param id 特权免押主键
     * @return 特权免押
     */
    @Override
    public TPrivilegeVerification selectTPrivilegeVerificationById(String id)
    {
        return tPrivilegeVerificationMapper.selectTPrivilegeVerificationById(id);
    }

    /**
     * 查询特权免押列表
     * 
     * @param tPrivilegeVerification 特权免押
     * @return 特权免押
     */
    @Override
    public List<TPrivilegeVerification> selectTPrivilegeVerificationList(TPrivilegeVerification tPrivilegeVerification)
    {
        return tPrivilegeVerificationMapper.selectTPrivilegeVerificationList(tPrivilegeVerification);
    }

    /**
     * 新增特权免押
     * 
     * @param tPrivilegeVerification 特权免押
     * @return 结果
     */
    @Override
    public int insertTPrivilegeVerification(TPrivilegeVerification tPrivilegeVerification)
    {
        tPrivilegeVerification.setCreateTime(DateUtils.getNowDate());
        return tPrivilegeVerificationMapper.insertTPrivilegeVerification(tPrivilegeVerification);
    }

    /**
     * 修改特权免押
     * 
     * @param tPrivilegeVerification 特权免押
     * @return 结果
     */
    @Override
    public int updateTPrivilegeVerification(TPrivilegeVerification tPrivilegeVerification)
    {
        tPrivilegeVerification.setUpdateTime(DateUtils.getNowDate());
        return tPrivilegeVerificationMapper.updateTPrivilegeVerification(tPrivilegeVerification);
    }

    /**
     * 批量删除特权免押
     * 
     * @param ids 需要删除的特权免押主键
     * @return 结果
     */
    @Override
    public int deleteTPrivilegeVerificationByIds(String[] ids)
    {
        return tPrivilegeVerificationMapper.deleteTPrivilegeVerificationByIds(ids);
    }

    /**
     * 删除特权免押信息
     * 
     * @param id 特权免押主键
     * @return 结果
     */
    @Override
    public int deleteTPrivilegeVerificationById(String id)
    {
        return tPrivilegeVerificationMapper.deleteTPrivilegeVerificationById(id);
    }

    /**
     * 获取风控报告
     * 
     * @param id 特权免押主键
     * @return 结果
     */
    @Override
    public String reportTPrivilegeVerificationById(String id)
    {
        TPrivilegeVerification tPrivilegeVerification = tPrivilegeVerificationMapper.selectTPrivilegeVerificationById(id);
        if(tPrivilegeVerification == null) {
            throw new RuntimeException("找不到此认证信息");
        }
        //获取配置信息
        TPlatformInfo tPlatformInfo = tPlatformInfoMapper.selectTPlatformInfoByOrder();
        if(tPlatformInfo == null) {
            throw new RuntimeException("找不到配置信息");
        }
        //这里如果有数据则直接从新拿取
        if(!"".equals(tPrivilegeVerification.getReportId()) && tPrivilegeVerification.getReportId() != null) {
            long timestamp = System.currentTimeMillis()/1000;
            System.out.println("当前时间戳（毫秒）: " + timestamp);
            Map<String, String> map = new HashMap<>();
            map.put("appid", tPlatformInfo.getReportZuxianzhiAppid());
            map.put("request_id", tPrivilegeVerification.getReportId());
            map.put("timestamp",timestamp+"" );//时间戳
            String signstr = sign(map,tPlatformInfo.getReportZuxianzhiSecret());
            String requestParams = "appid="+tPlatformInfo.getReportZuxianzhiAppid()+"&"+
                    "sign="+signstr+"&"+
                    "request_id="+tPrivilegeVerification.getReportId()+"&"+
                    "timestamp="+(timestamp+"");
            
            String result = HttpUtils.sendPost("https://v1.yicha.xin/act/api_report_build", requestParams);
            JSONObject yichaData = JSON.parseObject(result);
            if(!StringUtils.equals(yichaData.getString("code"), "0")) {
                throw new RuntimeException(yichaData.getString("msg"));
            }
            return yichaData.getJSONObject("data").getString("url");
        }
        String type = tPlatformInfo.getPrivilegeLevel();
        
        Map<String, String> map = new HashMap<>();
        map.put("appid", tPlatformInfo.getReportZuxianzhiAppid());
        map.put("idcardno", tPrivilegeVerification.getCertificateNumber());
        map.put("name", tPrivilegeVerification.getRealName());
        map.put("telephone", tPrivilegeVerification.getMobile());
        map.put("type", type);
        map.put("trueman", "1");
        map.put("force", "2");
        String signstr = sign(map,tPlatformInfo.getReportZuxianzhiSecret());
        
        String requestParams = "appid="+tPlatformInfo.getReportZuxianzhiAppid()+"&"+
            "sign="+signstr+"&"+
            "telephone="+tPrivilegeVerification.getMobile()+"&"+
            "name="+tPrivilegeVerification.getRealName()+"&"+
            "idcardno="+tPrivilegeVerification.getCertificateNumber()+"&"+
            "type="+type+"&trueman=1&force=2";
        
        String result = HttpUtils.sendPost("https://v1.yicha.xin/act/api_report_get", requestParams);
        JSONObject yichaData = JSON.parseObject(result);
        if(!StringUtils.equals(yichaData.getString("code"), "0")) {
            throw new RuntimeException(yichaData.getString("msg"));
        }
        //更新report_id报告ID
        tPrivilegeVerification.setReportId(yichaData.getString("report_id"));
        tPrivilegeVerificationMapper.updateTPrivilegeVerification(tPrivilegeVerification);
        return yichaData.getJSONObject("data").getString("url");
    }
    
    public String sign(final Map<String, String> data,String secret) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            if (String.valueOf(data.get(keyArray[i])).length() > 0) {
                sb.append(data.get(keyArray[i]));
            }
        }
        sb.append(secret);
        System.out.print(sb.toString());
        return DigestUtils.md5Hex(sb.toString());
    }
}
